//
//  CoreUserTextFieldComponent.m
//  CoreUser
//
//  Created by Demi on 20/04/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "CoreUserTextFieldComponent.h"

#import <base/base.h>

#import <Masonry/Masonry.h>
#import <ReactiveObjC/ReactiveObjC.h>

#define TEXTFIELD_HEIGHT 20.F
#define TEXTFIELD_BOTTOM_MARGIN 8.F
#define PLACEHOLDER_TRANSFORM 20.f

#define ANIMATION_DURATION 0.25f

const CGFloat CoreUserTextFieldComponentExpectedHeight = TEXTFIELD_HEIGHT + TEXTFIELD_BOTTOM_MARGIN + PLACEHOLDER_TRANSFORM;

@interface CoreUserTextFieldComponent ()

@property (nonatomic, assign) BOOL placeholderRaised;

@property (nonatomic, strong) UILabel *placeholderLabel;
@property (nonatomic, strong) UILabel *errorLabel;

@end

@implementation CoreUserTextFieldComponent

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self prepare];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
        [self prepare];
    }
    return self;
}

- (void)prepare
{
    [self drawSeparatorLineToPosition:UIRectEdgeBottom lineWidth:1.f];
    [self configureSubviews];
    [self placeSubviews];
    [self configureRX];
    [self updateErrorStyles];
    [self updatePlaceholderStyles];
}

- (void)configureSubviews
{
    CoreUserTextField *textField = [[CoreUserTextField alloc] init];
    _textField = textField;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.font = [UIFont systemFontOfSize:UIFontSmallSize];
    [self addSubview:textField];
    
    UILabel *placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel = placeholderLabel;
    _placeholderLabel.textColor = [UIColor lightTextColor];
    [self addSubview:placeholderLabel];
    
    UILabel *errorLabel = [[UILabel alloc] init];
    _errorLabel = errorLabel;
    _errorLabel.backgroundColor = [UIColor whiteColor];
    errorLabel.textColor = [UIColor redColor];
    errorLabel.font = [UIFont systemFontOfSize:UIFontSmallSize];
    [self addSubview:errorLabel];
}

- (void)placeSubviews
{
    [self.textField mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.leading.and.trailing.equalTo(self);
        maker.bottom.equalTo(self).offset(-TEXTFIELD_BOTTOM_MARGIN);
        maker.height.mas_equalTo(TEXTFIELD_HEIGHT);
    }];
    
    [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.leading.and.trailing.and.top.and.bottom.equalTo(self.textField);
    }];
    
    [self.errorLabel mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.leading.and.trailing.and.top.and.bottom.equalTo(self.textField);
    }];
}

- (void)configureRX
{
    @weakify(self);
    
    [self.tx_tapGestureRecognizer.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        @strongify(self);
        if (!self.textField.isFirstResponder)
        {
            [self.textField becomeFirstResponder];
        }
    }];
    
    RACSignal *textChangedSignal = [RACSignal merge:@[[self.textField rac_signalForControlEvents:UIControlEventEditingChanged],
                                     [self.textField rac_signalForSelector:@selector(setText:)]]];
    
    [textChangedSignal subscribeNext:^(id _Nullable x) {
        @strongify(self);
        BOOL shouldRaise = self.textField.text.length > 0;
        if (shouldRaise != self.placeholderRaised)
        {
            self.placeholderRaised = shouldRaise;
            [UIView animateWithDuration:ANIMATION_DURATION animations:^{
                @strongify(self);
                [self updatePlaceholderStyles];
            }];
        }
    }];

    [[self.textField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        if (self.invalid)
        {
            self.invalid = NO;
        }
    }];
    
    [[RACObserve(self, invalid) skip:1] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        
        if (self.invalid && self.textField.isFirstResponder)
        {
            [self.textField resignFirstResponder];
        }
        
        BOOL shouldRaise = self.invalid || self.textField.text.length > 0;
        BOOL raiseChanged = self.placeholderRaised != shouldRaise;
        if (raiseChanged)
        {
            self.placeholderRaised = shouldRaise;
        }
        [UIView animateWithDuration:ANIMATION_DURATION animations:^{
            @strongify(self);
            if (raiseChanged)
            {
                [self updatePlaceholderStyles];
            }
            [self updateErrorStyles];
        }];
    }];
}

- (void)setPlaceholderRaised:(BOOL)placeholderRaised animated:(BOOL)animated
{
    if (self.placeholderRaised == placeholderRaised)
    {
        return;
    }
    self.placeholderRaised = placeholderRaised;
    
    void(^updating)(void) = ^{
        
    };
    
    if (animated)
    {
        [UIView animateWithDuration:ANIMATION_DURATION animations:updating];
    }
    else
    {
        updating();
    }
}

- (void)updatePlaceholderStyles
{
    if (self.placeholderRaised)
    {
        self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, -PLACEHOLDER_TRANSFORM);
        self.placeholderLabel.font = [UIFont boldSystemFontOfSize:UIFontExtraSmallSize];
    }
    else
    {
        self.placeholderLabel.transform = CGAffineTransformIdentity;
        self.placeholderLabel.font = [UIFont systemFontOfSize:UIFontSmallSize];
    }
}

- (void)updateErrorStyles
{
    if (self.isInvalid)
    {
        self.textField.textColor = [UIColor clearColor];
        self.errorLabel.hidden = NO;
    }
    else
    {
        self.textField.textColor = [UIColor darkGrayTextColor];
        self.errorLabel.hidden = YES;
    }
}


@end
